package leetcode;

import java.util.*;

public class l0350_两个数组的交集_II_优化 {


    public int[] intersect(int[] nums1, int[] nums2) {
        //1 前置校验
        if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
            return new int[0];
        }
        //2 业务逻辑处理
        //默认选 数组长度小 nums1 放进映射表
        if (nums1.length > nums2.length) {
            return intersect(nums2, nums1);
        }
        Map<Integer, Integer> dataMap = new HashMap<>();
        for (int value : nums1) {
            Integer count = dataMap.getOrDefault(value, 0);
            dataMap.put(value, count + 1);
        }

        List<Integer> resultList = new ArrayList<>();
        for (int key : nums2) {
            Integer value = dataMap.get(key);
            if (value != null && value > 0) {
                resultList.add(key);
                dataMap.put(key, value - 1);
            }
        }
        int[] resultArr = new int[resultList.size()];
        int resultIndex = 0;
        for (int value : resultList) {
            resultArr[resultIndex++] = value;
        }
        return resultArr;
    }
}

